package com.math.aistudykbr.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class HttpUtil {
    public static String post(String url, String param, String apiKey, String secretKey) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);

        // 设置请求头
        String auth = apiKey + ":" + secretKey;
        String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
        httpPost.setHeader("Authorization", "Basic " + encodedAuth);
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

        // 设置请求体
        StringEntity entity = new StringEntity(param, StandardCharsets.UTF_8);
        httpPost.setEntity(entity);

        // 执行请求
        try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                String result = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
                // 验证响应是否包含错误
                JSONObject jsonResult = new JSONObject(result);
                if (jsonResult.has("error_code")) {
                    throw new Exception("OCR API Error: " + jsonResult.getString("error_msg"));
                }
                return result;
            }
            throw new Exception("Empty response from OCR API");
        } finally {
            httpClient.close();
        }
    }
}